﻿using MySql.Data.MySqlClient;
using NLog.Fluent;
using SHDM.Web.DataAccess;
using SHDM.Web.Infrastructure;
using SHDM.Web.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;
using static SHDM.Web.Models.ModelState;

namespace SHDM.Web.Controllers
{
    [Authenticator]
    [RoutePrefix("api/File")]
    public class FileController : ApiBaseController
    {
        readonly List<string> FileOrderBy = new List<string>() { "FILENAME","SIZE", "LASTUPDATEDATE" };
        readonly List<string> FileASC = new List<string>() { "ASC", "DESC"};
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="folderId">文件夹ID</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Upload")]
        public Result Upload(int folderId)
        {
            var db = new SHDMEntities();
            if (folderId > 0 && !db.sh_folders.Any(e => e.ID == folderId))
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "选择的文件夹不存在" };
            }
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                List<sh_files> lstFile = new List<sh_files>();
                for (var i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                {
                    var pf = HttpContext.Current.Request.Files[i];
                    string fileExt = Path.GetExtension(pf.FileName).ToLower();
                    var fileID = Guid.NewGuid().ToString();
                    string fileName = $"{fileID}{fileExt}.dat";

                    string noSufixFileName = Path.GetFileNameWithoutExtension(pf.FileName);//不带文件格式的文件名
                    string folderUrl = string.Format("/Files/{0}/", DateTime.Now.ToString("yyyyMMdd"));
                    string folder = HttpContext.Current.Server.MapPath(folderUrl);
                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }
                    pf.SaveAs(HttpContext.Current.Server.MapPath(string.Format("{0}{1}", folderUrl, fileName)));

                    if (db.sh_files.Any(e => e.FileName == noSufixFileName + fileExt))
                    {
                        var lstName = db.sh_files.Where(e => e.FileName.StartsWith(noSufixFileName + "(")).Select(e => e.FileName).ToList();
                        if (lstName != null && lstName.Count > 0)
                        {
                            var j = 1;
                            while (true)
                            {
                                if (!lstName.Contains($"{noSufixFileName}({j}){fileExt}"))
                                {
                                    noSufixFileName = $"{noSufixFileName}({j})";
                                    break;
                                }
                                j++;
                            }
                        }
                        else
                        {
                            noSufixFileName = $"{noSufixFileName}(1)";
                        }
                    }
                    lstFile.Add(new sh_files()
                    {
                        ID = fileID,
                        FileName = $"{noSufixFileName}{fileExt}",
                        Ext = fileExt,
                        FolderID = (folderId < 0 ? 0 : folderId),
                        Path = $"{folderUrl}{fileName}",
                        Size = pf.ContentLength,
                        State = FileState.Active,
                        CreateBy = this.AccountInfo.ID,
                        CreateDate = DateTime.Now,
                        LastUpdateBy = this.AccountInfo.ID,
                        LastUpdateDate = DateTime.Now
                    });
                }
                if (lstFile != null && lstFile.Count > 0)
                {
                    db.sh_files.AddRange(lstFile);
                    db.SaveChanges();
                }
                return new Result() { ErrorCode = 0, ErrorMessage = "上传成功", Data = lstFile };
            }
            return new Result() { ErrorCode = 1, ErrorMessage = "请选择上传文件" };
        }

        /// <summary>
        /// 获取文件夹中所有文件
        /// </summary>
        /// <param name="folderId"></param>
        /// <param name="orderby"></param>
        /// <param name="asc">
        /// 0=正序
        /// 1-倒序
        /// </param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetFolderFiles")]
        public Result GetFolderFiles([FromBody]List<string> exts, int folderId, string orderby, string asc, string search, int state)
        {
            List<MySqlParameter> parms = new List<MySqlParameter>();
            StringBuilder cmd = new StringBuilder();

            if (folderId >= 0)
            {
                cmd.Append($"SELECT * FROM SH_FILES_V WHERE STATE={state} AND FOLDERID={folderId}");
            }
            else
            {
                cmd.Append($"SELECT * FROM SH_FILES_V WHERE STATE={state}");
            }

            if (exts != null && exts.Count > 0)
            {
                cmd.Append($" AND EXT IN(");
                exts.ForEach(e =>
                {
                    cmd.Append($"@EXTS_{exts.IndexOf(e)},");
                    parms.Add(new MySqlParameter()
                    {
                        ParameterName = $"@EXTS_{exts.IndexOf(e)}",
                        Value = e
                    });
                });
                cmd.Remove(cmd.Length - 1, 1);
                cmd.Append(")");
            }

            if (this.AccountInfo.Role != sh_users.Roles.Admin)
            {
                var lstDept = sh_dept.GetParents(this.AccountInfo.DeptID);
                cmd.Append($" AND DEPTID IN({string.Join(",", lstDept.Select(e => e.ID).ToArray())},0)");
            }

            if (!string.IsNullOrEmpty(search))
            {
                cmd.Append($" AND FILENAME LIKE '%@SEARCH%'");
                parms.Add(new MySqlParameter()
                {
                    ParameterName = $"@SEARCH",
                    Value = search
                });
            }
            if (!string.IsNullOrEmpty(orderby) && FileOrderBy.Contains(orderby.ToUpper()))
            {
                cmd.Append($" ORDER BY {orderby}");
                if (!string.IsNullOrEmpty(asc) && FileASC.Contains(asc.ToUpper()))
                {
                    cmd.Append($" {asc}");
                }
            }
            return new Result() { Data = new SHDMEntities().SqlQueryDicReader(cmd.ToString(),parms.ToArray()) };
        }

        [HttpPost]
        [Route("RecyclingFiles")]
        public Result RecyclingFiles(List<string> listID)
        {
            var db = new SHDMEntities();
            var lst = db.sh_files.Where(e => listID.Contains(e.ID) && e.State == FileState.Active).ToList();
            if (lst != null && lst.Count > 0)
            {
                lst.ForEach(row =>
                {
                    //row.State = FileState.Delete;
                    //row.LastUpdateBy = this.AccountInfo.ID;
                    //row.LastUpdateDate = DateTime.Now;
                    try
                    {
                        File.Delete(HttpContext.Current.Server.MapPath(row.Path));
                    }catch (Exception ex) {
                        Log.Error(ex.ToString());
                    }
                });
                db.sh_files.RemoveRange(lst);
                db.SaveChanges();
            }
            return new Result() { ErrorMessage = "操作成功" };
        }

        [HttpGet]
        [Route("ModifyFileName")]
        public Result ModifyFileName(string id, string fileName)
        {
            var db = new SHDMEntities();
            var entity = db.sh_files.FirstOrDefault(e => e.ID == id);
            if (entity == null)
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "文件不存在" };
            }

            string fileExt = Path.GetExtension(fileName).ToLower();
            string noSufixFileName = Path.GetFileNameWithoutExtension(fileName);//不带文件格式的文件名
            if (db.sh_files.Any(e => e.FileName == (noSufixFileName + fileExt) && e.ID != id))
            {
                var lstName = db.sh_files.Where(e => e.FileName.StartsWith(noSufixFileName + "(")).Select(e => e.FileName).ToList();
                if (lstName != null && lstName.Count > 0)
                {
                    var j = 1;
                    while (true)
                    {
                        if (!lstName.Contains($"{noSufixFileName}({j}){fileExt}"))
                        {
                            noSufixFileName = $"{noSufixFileName}({j})";
                            break;
                        }
                        j++;
                    }
                }
                else
                {
                    noSufixFileName = $"{noSufixFileName}(1)";
                }
            }
            entity.FileName = $"{noSufixFileName}{fileExt}";
            entity.Ext = fileExt;
            entity.LastUpdateDate = DateTime.Now;
            entity.LastUpdateBy = this.AccountInfo.ID;
            db.SaveChanges();
            return new Result() { ErrorMessage = "操作成功", Data = entity };
        }
    }
}